package com.example.idea.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.idea.entity.User;
import com.example.idea.service.UserService;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * 功能：token生成和校验
 * 作者：妙笔生花
 * 日期：2024/9/9 8:45
 */

@Component
public class TokenUtils {

    private static UserService staticUserService;

    @Autowired
    UserService userService;

    @PostConstruct
    public void setUserService() {
        staticUserService = userService;
    }

    /**
     * 生成token,该token长度不一致,如需一致,可自行MD5或者其它方式加密一下
     *
     * @return
     */
    public static String createToken(Integer userId, String sign) {
        return JWT.create().withAudience(String.valueOf(userId))  //将userId 保存在token里面，以方便根据token直接拿到userId来查询数据库
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2))  //两个小时token过期
                .sign(Algorithm.HMAC256(sign)); //以password 作为 token 的密钥
    }

    /**
     * 获取当前登录的用户信息
     */
    public static User getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserService.getById(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}



